const util = require('../../utils/util.js');
const pageUtil = require('../../utils/page.js');
const app = getApp()

Page({
  accountInfos: new Map(),
  fetchingData: false,
  requireNextPage: false,
  data: {
    offset: 0,
    pageSize: 0,
    totalSize: 1,
    receiveCount: 10,
    withdrawCount: 2,
    receiveValue: 0,
    bills: [{
      title: 'title',
      suffix: "suffix",
      date: util.formatDateTime(new Date()),
      value: util.formatChineseCurrency(100)
    }, {
      title: 'title',
      suffix: "suffix",
      date: util.formatDateTime(new Date()),
      value: util.formatChineseCurrency(100)
    }]
  },

  onReady: function () {
    const userInfo = app.globalData.userInfo;
    const page = this;
    // app.changeStyle(page);
    pageUtil.startLoading(page);
    page.accountInfos.set(app.globalData.accountId, {
      name: userInfo.nickName,
      avatar: userInfo.avatarUrl
    });
    wx.request({
      url: app.processUri('accounts/_/payments/statistics'),
      method: "GET",
      header: { 'Authorization': app.globalData.accessToken },
      success: (res) => {
        page.setData({
          receiveCount: res.data.receiveCount,
          withdrawCount: res.data.withdrawCount,
          receiveValue: util.formatChineseCurrency(res.data.receiveValue)
        });
      }
    });
    this.fetchNextPage();
  },

  openPost: function (e) {
    const postId = e.currentTarget.dataset.id;
    // if (postId > 0) {
    //   wx.navigateTo({ url: '../detail/detail?postId=' + postId });
    // }
  },

  hasNextPage: function () {
    return this.data.offset + this.data.pageSize < this.data.totalSize;
  },

  fetchNextPage: function () {
    let page = this;
    if (!page.hasNextPage()) return;
    if (page.fetchingData) {
      page.requireNextPage = true;
      return;
    }
    page.fetchingData = true;
    wx.request({
      url: app.processUri('accounts/_/payments/receive'),
      method: "GET",
      header: { 'Authorization': app.globalData.accessToken, 'offset': page.data.offset },
      success: function (res) {
        const header = res.header;
        page.setData({
          totalSize: parseInt(header.totalSize),
          pageSize: parseInt(header.size),
          offset: parseInt(header.offset)
        });
        const data = res.data;
        const tempAccount = { name: '', avatar: '' };
        if (data.length > 0) {
          const result = [];
          const needFetchInfoAccountIds = [];
          if (page.data.bills.length > 0) {
            result.push(page.data.bills);
          }
          for (var i = 0; i < data.length; i++) {
            let payment = data[i];
            let account = page.accountInfos.get(payment.accountId);
            if (account == null) {
              if (needFetchInfoAccountIds.indexOf(payment.accountId) < 0) {
                needFetchInfoAccountIds.push(payment.accountId);
              }
              account = tempAccount;
            }
            result.push({
              id: payment.id,
              avatar: account.avatar,
              suffix: payment.value > 0 ? '向你打赏' : '发起提现',
              title: account.name,
              date: util.formatDateTime(new Date(payment.createTime)),
              value: util.formatChineseCurrency(payment.value),
              accountId: payment.accountId,
              postId: payment.paymentPostId,
              status: payment.status
            });
          }
          if (needFetchInfoAccountIds.length > 0) {
            const url = app.processUri('accounts?ids=' + needFetchInfoAccountIds.join('&ids='));
            wx.request({
              url: url,
              method: "GET",
              header: { 'Authorization': app.globalData.accessToken },
              success: (res) => {
                if (res.data != null) {
                  res.data.forEach(value => {
                    page.accountInfos.set(value.id, value);
                  });
                  result.forEach(value => {
                    let account = page.accountInfos.get(value.accountId);
                    if (account != null) {
                      value.avatar = account.avatar;
                      value.title = account.name;
                    }
                  });
                  page.setData({
                    bills: result
                  });
                }
              }
            });
          }
          page.setData({
            bills: result
          });
        }
      },
      complete: () => {
        page.fetchingData = false;
        pageUtil.stopLoading(page);
        if (page.requireNextPage) {
          page.requireNextPage = false;
          page.fetchNextPage();
        }
      }
    });
  }

})
